<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { LoginPwdReq } from '@/apis/common/loginApi'
import { reactive, ref } from 'vue'
import { loginApi } from '@/apis/common/loginApi'

const emits = defineEmits(['success'])
const formData = ref<Partial<LoginPwdReq>>({ loginType: 'PWD' })
const formRef = ref<FormInstance>()
const formRules = reactive<FormRules<LoginPwdReq>>({
  loginName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  loginPwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captchaCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})
const loading = ref(false)

function onSubmit() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const data = await loginApi.login(formData.value)
        emits('success', data)
      }
      finally {
        loading.value = false
      }
    }
  })
}

const showCaptchaCode = ref(false)
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-position="right"

    scroll-to-error hide-required-asterisk
    size="large"
    @submit.prevent
  >
    <el-form-item prop="loginName">
      <el-input
        v-model="formData.loginName"
        placeholder="用户名"
      />
    </el-form-item>
    <el-form-item prop="loginPwd">
      <el-input
        v-model="formData.loginPwd"
        show-password
        placeholder="密码"
        type="password"
      />
    </el-form-item>
    <el-form-item
      v-if="showCaptchaCode"
      prop="captchaCode"
    >
      <div class="w-full flex flex-row">
        <el-input
          v-model="formData.captchaCode"
          class="flex-grow"
          placeholder="验证码"
        />
        <el-image
          class="border"
          src=""
        />
      </div>
    </el-form-item>

    <el-form-item class="w-full">
      <el-button
        type="primary"
        class="w-full"
        native-type="submit"
        @click="onSubmit"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>
